package com.ywq.app.domain;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class OnLineUserListener implements HttpSessionBindingListener {

	private final static Logger logger = LoggerFactory
			.getLogger(OnLineUserListener.class);

	private Member member = null;

	public Member getMember() {
		return member;
	}

	public OnLineUserListener(Member member) {
		this.member = member;
	}

	@SuppressWarnings("unchecked")
	public void valueBound(HttpSessionBindingEvent event) {
		HttpSession session = event.getSession();
		ServletContext application = session.getServletContext();
		// 把用户名放入在线列表
		List<OnlineUser> onlineUserList = (List<OnlineUser>) application
				.getAttribute("onlineUserList");
		// 第一次使用前，需要初始化
		if (null == onlineUserList) {
			onlineUserList = new ArrayList<OnlineUser>();
			application.setAttribute("onlineUserList", onlineUserList);
		}
		OnlineUser user = new OnlineUser(member, new Date());
		onlineUserList.add(user);
		if (logger.isDebugEnabled()) {
			logger.debug(member.getNickname() + " Login!");
		}
		// TODO 如果session占用的内存很大，需要做持久化
		String memberId = member.getId();
		application.setAttribute(memberId, session);
	}

	@SuppressWarnings("unchecked")
	public void valueUnbound(HttpSessionBindingEvent event) {
		HttpSession session = event.getSession();
		ServletContext application = session.getServletContext(); 
		// 从在线列表中删除用户名
		List<OnlineUser> onlineUserList = (List<OnlineUser>) application
				.getAttribute("onlineUserList");
		if (null != onlineUserList && onlineUserList.size() > 0) {
			for (OnlineUser user : onlineUserList) {
				if (user.getMember().getId().equals(member.getId())) {
					if (logger.isDebugEnabled()) {
						logger.debug(member.getNickname() + " Logout!Time: "
								+ new Date());
					}
					onlineUserList.remove(user);
					// TODO 删除session
					String memberId = member.getId();
					application.removeAttribute(memberId);
					break;
				}
			}
		}

	}

}
